const boom = require('@hapi/boom');

const GROUP_NAME = 'init';
exports.plugin = {
  name: 'routerInstall',
  async register(server) {
    const initUsers = {
      method: 'get',
      path: `/${GROUP_NAME}/users`,
      handler: async (req) => {
        const rootUser = {
          username: 'root',
          password: '123123',
          phone: '18013838666',
          email: 'root@qq.com',
          gender: 1,
          group: [],
        };
        const usernameExist = await req.usersModel.isExist(
          'username',
          rootUser.username
        );
        if (usernameExist) {
          return boom.badRequest('初始化已经完成');
        }
        const emailExist = await req.usersModel.isExist(
          'email',
          rootUser.email
        );
        if (emailExist) {
          return boom.badRequest('邮箱已存在');
        }
        const phoneExist = await req.usersModel.isExist(
          'phone',
          rootUser.phone
        );
        if (phoneExist) {
          return boom.badRequest('手机已存在');
        }
        const result = await req.usersModel.addUsers(rootUser);
        return result;
      },
      config: {
        notes: '初始化用户',
        description: '初始化用户',
        tags: ['api', GROUP_NAME],
        auth: false,
      },
    };
    await server.route([initUsers]);
  },
};
